// Global variables
var CanvasXSize = 800;
var CanvasYSize = 200;
var UpdateSpeed = 50; // update time in ms

var Blob1X = 100;
var Blob1Y = 100;
var Blob1Direction = Math.PI/4;
var Blob1Size = 25;

function init()
{
  //Set Refresh Rate
  return setInterval(loop, UpdateSpeed);
}

function loop()
{
  //Cause square to rotate
  Blob1Direction = Blob1Direction+0.1;
  //Blob1X = Blob1X+1;
  draw();
  //Blob1Direction = Math.PI/4;
}

function draw()
{
  var buffer = document.createElement('canvas');
  var canvas = document.getElementById('visible-canvas');
  buffer.width = canvas.width;
  buffer.height = canvas.height;
  
  buffer_context = buffer.getContext('2d');
  var context = canvas.getContext('2d');
  
  //Draw our square into the buffer_context
  draw_square(buffer_context);
  //Clear buffer
  context.clearRect(0, 0, canvas.width, canvas.height);
  //Draw the buffer to the screen
  context.drawImage(buffer, 0, 0);
}

function draw_square(context)
{
  // calculate the deltaX and deltaYs based of the direction
  var DeltaX = Math.cos(Blob1Direction)*Blob1Size;
  var DeltaY = Math.sin(Blob1Direction)*Blob1Size;
  // create line temps
  var TempX = 0;
  var TempY = 0;
  // draw our square
  context.beginPath();
  TempX = Blob1X+(Math.random()-0.5)*Blob1Size/50-Math.sin(Math.PI/4-Blob1Direction)*Math.sqrt(Blob1Size*Blob1Size/2);
  TempY = Blob1Y+(Math.random()-0.5)*Blob1Size/50-Math.cos(Math.PI/4-Blob1Direction)*Math.sqrt(Blob1Size*Blob1Size/2);
  context.moveTo(TempX, TempY);
  TempX = TempX+DeltaX;
  TempY = TempY+DeltaY;
  context.lineTo(TempX, TempY);
  TempX = TempX-DeltaY;
  TempY = TempY+DeltaX;
  context.lineTo(TempX, TempY);
  TempX = TempX-DeltaX;
  TempY = TempY-DeltaY;
  context.lineTo(TempX, TempY);
  context.closePath();
  context.fill();
}
